import wsgiref.handlers
import sys
import os
import string
import codecs
import geohash
import random
import re
import cgi
import datetime
import time
import math
import pickle
import logging

DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
LIB_PATH = os.path.join(DIR_PATH, "lib")
EXTRA_PATHS = []
for path in os.listdir(LIB_PATH):
    fullpath = os.path.join(LIB_PATH, path)
    if os.path.isdir(fullpath) and not path.startswith("."):
        EXTRA_PATHS.append(fullpath)
sys.path = sys.path + EXTRA_PATHS

from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import search
from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import urlfetch
from datetime import datetime, timedelta
from django.core import serializers
from django.http import HttpResponsePermanentRedirect
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.api import images 
from google.appengine.ext.db import GqlQuery
from modelslanguages import *
from utilities import *



class TermAction(webapp.RequestHandler):
  def get(self,termid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='delete':
     term=Term.get(termid)
     term.delete()
     self.redirect("/languages/", False)
     return 1
   elif action=='edit':
     term=Term.get(termid)
     querylanguage = Language.all()
     querylanguage.order('url')
     languages = querylanguage.fetch(100)
     querytermtype = TermType.all()
     querytermtype.order('url')
     termtypes = querytermtype.fetch(100)
     template_values = {
       'customuser': customuser,
       'term': term,
       'languages': languages,
       'termtypes': termtypes,
       'termtype': term.termtype.url,
       'language': term.language.url,
       'path': "/languages/terms/"+termid+"/save/",
     }
   elif action=='new':
     querylanguage = Language.all()
     querylanguage.order('url')
     languages = querylanguage.fetch(100)
     querytermtype = TermType.all()
     querytermtype.order('url')
     termtypes = querytermtype.fetch(100)
     template_values = {
       'customuser': customuser,
       'languages': languages,
       'termtypes': termtypes,
       'termtype': 'noun',
       'language': 'english',
       'path': "/languages/terms//save/",
     }

   path = os.path.join(os.path.dirname(__file__), 'admin/term.html')
   self.response.out.write(template.render(path, template_values))
     
  def post(self,termid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]

   if action=='save':
     if termid!='':
       term=Term.get(termid)
     else:
       term = Term()

     if self.request.get("save")!='':
       word = self.request.get("word")
       url = self.request.get("url")
       translate = self.request.get("translate")
       language = Language.get(self.request.get("language"))
       termtype = TermType.get(self.request.get("termtype"))
       term.word = word
       term.translate = translate
       term.url = url
       term.language = language
       term.termtype = termtype
       term.put()

     self.redirect("/languages/terms//new/", True)



class TermsList(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   queryterms = Term.all()
   queryterms.order('word')
   terms = queryterms.fetch(500)
   template_values = {
     'customuser': customuser,
     'terms': terms
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/terms.html')
   self.response.out.write(template.render(path, template_values))



class Printable(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   queryterms = Term.all()
   queryterms.order('word')
   terms = queryterms.fetch(500)
   template_values = {
     'customuser': customuser,
     'terms': terms
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/printable.html')
   self.response.out.write(template.render(path, template_values))



def main():
  application = webapp.WSGIApplication([('/languages/terms/(.*)/(edit)/', TermAction),
                                        ('/languages/terms/(.*)/(new)/', TermAction),
                                        ('/languages/terms/(.*)/(save)/', TermAction),
                                        ('/languages/terms/(.*)/(delete)/', TermAction),
                                        ('/languages/', TermsList),
                                        ('/languages/printable/', Printable)
                                        ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
